import React from 'react'
import { Menu, Divider } from 'antd'
import cloneDeep from 'clone-deep'
import { logoutFun } from '@utils/auth'
import { treeToArray } from '@/utils'

import styles from './Header.module.less'

const Header = ({ history, location, gState, setupMenuSelectedKeys }: any) => {
  const bg_img = `${process.env.PUBLIC_URL}/img/logo.png`
  const head_portrait = `${process.env.PUBLIC_URL}/img/head_portrait.png`
  const { userInfo, menuList, menuSelectedKeys } = gState

  // 菜单渲染
  const getMenus = (menuTreeN: menuItemType[] = []) => {
    const children = 'subMenuList', // 导航栏 子菜单字段(错误的字段即可不展示子菜单)
      id = 'menuCode'
    return menuTreeN.map((_: menuItemType) => {
      const subList = _[children as 'subMenuList'] || []
      if (subList && subList.length > 0) {
        return (
          <Menu.SubMenu key={_[id]} title={_['menuName']}>
            {getMenus(subList)}
          </Menu.SubMenu>
        )
      }
      return (
        <Menu.Item key={_[id]}>
          <div onClick={() => menuClick(_)}>{_['menuName']}</div>
        </Menu.Item>
      )
    })
  }

  // 菜单点击
  const menuClick = ({ menuCode, url }: menuItemType) => {
    setupMenuSelectedKeys([menuCode])
    history.push(url)
  }

  // 路由 选中菜单
  let selectedKeys: any[] = cloneDeep([...menuSelectedKeys])
  // let defaultSelectedKeys: any[] = []
  const menuArray = treeToArray(menuList, 'subMenuList')
  menuArray.forEach(({ menuCode, url }: menuItemType) => {
    if (selectedKeys.length < 1 && location.pathname.includes(url)) {
      selectedKeys.push(menuCode)
    }
  })

  return (
    <div className={styles['header_wrap']}>
      <div className={styles['title_section']}>
        <div className={styles['title']}>
          <div className={styles['left']}>
            <img src={bg_img} alt="" />
          </div>
          <div className={styles['right']}>
            <span>{userInfo.deptName}</span>
            <Divider type="vertical" />
            <div className={styles['user_info']}>
              {userInfo.staffId && (
                <img
                  src={
                    userInfo.staffImageUrl
                      ? userInfo.staffImageUrl
                      : head_portrait
                  }
                  alt=""
                />
              )}
              <span>{userInfo.staffFullName}</span>
            </div>
            <Divider type="vertical" />
            <span className={styles['logout']} onClick={() => logoutFun()}>
              退出
            </span>
          </div>
        </div>
      </div>
      <div className={styles['menus_section']}>
        <div className={styles['menus']}>
          <Menu mode="horizontal" selectedKeys={selectedKeys}>
            {getMenus(menuList)}
          </Menu>
        </div>
      </div>
    </div>
  )
}

export default Header
